package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/ExamListServlet")
public class ExamListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        Connectmysql conn = null;
        try {
            conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                String sql = "SELECT e.exam_id, e.exam_name, c.course_name, e.start_time, " +
                        "e.duration, e.status, e.apply_time, " +
                        "(SELECT GROUP_CONCAT(cl.class_name SEPARATOR ', ') " +
                        " FROM exam_class ec " +
                        " JOIN class cl ON ec.class_id = cl.class_id " +
                        " WHERE ec.exam_id = e.exam_id) AS class_names " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "WHERE e.teacher_id = ? " +
                        "ORDER BY e.apply_time DESC";

                ResultSet rs = conn.executeSql(sql, new Object[]{teacherId});
                StringBuilder json = new StringBuilder("[");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                boolean first = true;

                while (rs.next()) {
                    if (!first) {
                        json.append(",");
                    }
                    first = false;

                    json.append("{")
                            .append("\"exam_id\":").append(rs.getInt("exam_id")).append(",")
                            .append("\"exam_name\":\"").append(escapeJson(rs.getString("exam_name"))).append("\",")
                            .append("\"course_name\":\"").append(escapeJson(rs.getString("course_name"))).append("\",");

                    // 添加班级信息
                    String classNames = rs.getString("class_names");
                    json.append("\"class_names\":\"")
                            .append(escapeJson(classNames != null ? classNames : "未分配班级"))
                            .append("\",");

                    Timestamp startTime = rs.getTimestamp("start_time");
                    json.append("\"start_time\":\"")
                            .append(escapeJson(sdf.format(startTime)))
                            .append("\",");

                    int duration = rs.getInt("duration");
                    json.append("\"duration\":\"")
                            .append(duration)
                            .append("分钟\",");

                    int status = rs.getInt("status");
                    json.append("\"status\":\"")
                            .append(escapeJson(getStatusText(status)))
                            .append("\",")
                            .append("\"status_code\":")
                            .append(status)
                            .append(",");

                    Timestamp applyTime = rs.getTimestamp("apply_time");
                    json.append("\"apply_time\":\"")
                            .append(escapeJson(sdf.format(applyTime)))
                            .append("\"}");
                }
                json.append("]");

                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(json.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("teacher.jsp?section=exam&error=考试列表获取失败");
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    private String getStatusText(int status) {
        switch (status) {
            case 0: return "申请中";
            case 1: return "已批准";
            case 2: return "已激活";
            case 3: return "已结束";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}